package com.blog.config;

import com.blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Configuration
public class GatewayFilter implements GlobalFilter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (request.getURI().getPath().startsWith("/add") |
        request.getURI().getPath().startsWith("/edit") |
        request.getURI().getPath().startsWith("/delete")) {
            ServerHttpResponse response = exchange.getResponse();
            String token = request.getHeaders().getFirst("token");
            if (token != null) {
                String username = JwtUtils.decode(token).getSubject();
                if (redisTemplate.boundValueOps(username).get() != null) {
                    return chain.filter(exchange);
                }
            }
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);

    }
}
